/*
 * Valentine Gladstein
 * SOLAR ID 108731583
 * Homework #5
 * CSE214
 * Recitation 03-Phil Ammirato
 * Grading TA: Yanjie Li
 */

import java.io.*;
import java.util.*;

public class Tree {

    private TreeNode root;
    public TreeNode prevNode;
    public TreeNode curNode;

    public Tree(TreeNode inputNode) {
	root = inputNode;
    }

    /**
     * A helper method used internally to read user input from the standard input
     * @return a string containing the user's input
     */
    private String getInput() {
        String s = "";
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        try {
            s = br.readLine();

        } catch (IOException e) {}
        return s;
    }

    public boolean addNode(String label, String prompt, String message, String parentLabel) {
	TreeNode newNode = new TreeNode(label, message, prompt);
	TreeNode parentNode = getNodeReference(parentLabel, root);

	if (parentNode == null)
	    return false;
	return (parentNode.addChild(newNode));
    }

    public TreeNode getNodeReference(String label) {
	return getNodeReference(label, root);
    }

    private TreeNode getNodeReference(String label, TreeNode cursor) {
	if (cursor == null || cursor.getLabel().equals(label))
	    return cursor;
	for (int i = 0; i < cursor.numChildren(); i++) {
	    TreeNode temp = getNodeReference(label, cursor.getChild(i));
	    if (temp != null)
		return temp;
	}
	System.out.println("No node with label \"" + label + "\" was found.");
	return null;
    }

    public void preOrder() {
	if (root == null) {
	    System.out.println("Invalid tree cannot be traversed. Root must not be null.");
		 return;
	}
	preOrder(root);
    }

    private void preOrder(TreeNode cursor) {
	if (cursor == null)
	    return;	
	for (int i = 0; i < cursor.numChildren(); i++) {
	    System.out.println(cursor.getPrompt());
	    preOrder(cursor.getChild(i));
	}
    }
    
    public void beginSession() {   
	curNode = root;

	while (curNode.numChildren() != 0) {
	    System.out.println(curNode.getMessage());
	    for (int i = 0; i < curNode.numChildren(); i++) {
		System.out.println(i + ") " + curNode.getChild(i).getMessage()); 
		    }
	    System.out.print("Please make a selelction: ");
	    int temp = Integer.parseInt(getInput());
	    prevNode = curNode;
	    curNode = curNode.getChild(temp);
	}
	System.out.println("Thank you for using the system!");
    }
}

